package com.macro.mall.portal.filter;

import lombok.extern.log4j.Log4j2;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Map;

@Log4j2
@Order(1)
//@Configuration
@WebFilter(urlPatterns = "/*")
public class AuthorizeFilter implements Filter {

    public static final String MESSAGE = "message";

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
        long start = System.currentTimeMillis();
        log.info("=================== 过滤器开始工作 ===================");
        HttpServletRequest req = ((HttpServletRequest) request);
        request.setAttribute("start", start);
        log.info("id:" + start + "-url: " + req.getRequestURL().toString());

        //获得所有头的名字
        Enumeration<String> em = req.getHeaderNames();
        while (em.hasMoreElements()) {
            String key = em.nextElement();
            String value = req.getHeader(key);
            log.info("请求头：" + key + " : " + value);
        }
        String bodyString = HttpHelper.getBodyString(request);
        log.info("请求体：{}", bodyString);
        Map<String, String[]> map = request.getParameterMap();
        for (String parameter : map.keySet()) {
            log.info("请求参数为：" + parameter + " ," + map.get(parameter).toString());
        }
        filterChain.doFilter(request, response);
        log.info("id:" + start + "-总耗时 : " + (System.currentTimeMillis() - start) / 1000f + " 秒");
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void destroy() {
    }
}
